#!/usr/bin/env python
import sys
import itk	
import imageTools.ITKUtils.io as io
import imageTools.ITKUtils.ifilter as ifilter
import numpy as np
import os
import pylab as pb
from . import connectedThreshSeg

# get the threshold and seed point
def getThreshSeed(filtered_file, original_file):
    img = io.readImage(filtered_file)
    array = itk.PyBuffer.IF3.GetArrayFromImage(img)
    mask = np.where( array > 0, 1,0).astype(np.uint8)
    img = io.readImage(original_file) 
    img_array_1 = itk.PyBuffer.IF3.GetArrayFromImage(img)
    img_array = mask*img_array_1
    flat_array = img_array.flat
    index = np.where((flat_array > 100) & (flat_array<600))
    index = index[0]
    flat_array = flat_array[index]
    mean = np.mean(flat_array)
    std = np.std(flat_array)
    value = mean - 0.25*std 
    print mean
    seed = np.where( (array > mean) & ((img_array_1 > value  )& (img_array_1 < 400)))
    print img_array_1[seed]
    seed = np.transpose(seed)
    print seed
    return [value, seed] 

# count the number of voxels included in the segmentation
def count(filename):
    
    img = io.readImage(filename)
    array = itk.PyBuffer.IF3.GetArrayFromImage(img)
    count = np.sum(array)
    print count
    return count

def adaSeg(filtered_file, original_file, maskfile):
   thresh, seed =  getThreshSeed(filtered_file, original_file)
   thresh = int(thresh)
   thresh_high = 2000
   tmp = os.path.splitext(original_file)
   outputfile = str(tmp[0]) + "_seg" + ".mha"
   xx = int(len(seed)*0.5)
   counter = 0;
   for j in range(10):# change threshold 
      for i in range(min(len(seed), 3)):# change seed point 
         z, y, x = seed[( xx + 13*i + 2*j)%len(seed)]
         seedPoint = [x, y, z ] 
         thresh_high = 1000
         threshold = [thresh,thresh_high ]
         print original_file, maskfile, threshold, seedPoint
         connectedThreshSeg.run_seg(original_file, maskfile, threshold, seedPoint)  
         counter = count(outputfile)
         if counter > 1000000: #if we obtain a big strucutre, then exit the loop
            j = 10 
            break
      if counter >1500000: 
           break
      else:
           thresh = thresh -5 
         
   return outputfile

def main():
   adaSeg(sys.argv[1], sys.argv[2], sys.argv[3] ) 
if __name__ == '__main__':
    main()


